package com.tbl.modules.wms.controller.allo;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.google.common.collect.Maps;
import com.tbl.common.utils.DateUtils;
import com.tbl.common.utils.PageTbl;
import com.tbl.common.utils.PageUtils;
import com.tbl.common.utils.StringUtils;
import com.tbl.modules.platform.constant.MenuConstant;
import com.tbl.modules.platform.controller.AbstractController;
import com.tbl.modules.platform.service.system.RoleService;
import com.tbl.modules.platform.util.DeriveExcel;
import com.tbl.modules.wms.constant.Constant;
import com.tbl.modules.wms.entity.allo.Allocation;
import com.tbl.modules.wms.entity.baseinfo.Warehouse;
import com.tbl.modules.wms.service.allo.AllocationDetailService;
import com.tbl.modules.wms.service.allo.AllocationService;
import com.tbl.modules.wms.service.baseinfo.WarehouseService;
import com.tbl.modules.wms.service.move.MoveStorageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.DecimalFormat;
import java.util.*;


/**
 * 库存调拨:调拨单管理
 * @author 70486
 */
@Controller
@RequestMapping("/allotCon")
public class AlloController extends AbstractController {

    /**
     * 调拨管理-调拨表
     */
    @Autowired
    private AllocationService allocationService;
    /**
     * 调拨管理-调拨明细
     */
    @Autowired
    private AllocationDetailService allocationDetailService;
    /**
     * 角色
     */
    @Autowired
    private RoleService roleService;
    /**
     * 仓库
     */
    @Autowired
    private WarehouseService warehouseService;
    /**
     * 移库单
     */
    @Autowired
    private MoveStorageService moveStorageService;

    /**
     * 跳转到调拨单管理列表页
     * @return ModelAndView
     */
    @RequestMapping("/allotListView")
    public ModelAndView allotListView() {
        ModelAndView mv = this.getModelAndView();
        mv.addObject("operationCode", roleService.selectOperationByRoleId(getSessionUser().getRoleId(), MenuConstant.allotCon));
        mv.setViewName("techbloom/allo/alloinfo/alloinfo_list");
        return mv;
    }

    /**
     * 调拨单管理列表页数据
     * @param queryJsonString 查询条件
     * @return Map<String,Object>
     */
    @RequestMapping(value = "/alloctionPageList.do")
    @ResponseBody
    public Map<String, Object> alloctionPageList(String queryJsonString) {
        Map<String, Object> map = new HashMap<>(4);
        if (!StringUtils.isEmptyString(queryJsonString)) {
            map = JSON.parseObject(queryJsonString);
        }
        PageTbl page = this.getPage();
        PageUtils utils = allocationService.getPageList(page, map);
        page.setTotalRows(utils.getTotalCount() == 0 ? 1 : utils.getTotalCount());
        //初始化分页对象
        executePageMap(map, page);
        map.put("rows", utils.getList());
        map.put("total", utils.getTotalPage() == 0 ? 1 : utils.getTotalPage());
        return map;
    }

    /**
     * 点击新增跳转到新增页面
     * @return MpdelAndView
     */
    @RequestMapping(value = "/toAdd.do")
    @ResponseBody
    public ModelAndView toAdd() {
        ModelAndView mv = this.getModelAndView();
        mv.setViewName("techbloom/allo/alloinfo/alloinfo_add");
        return mv;
    }

    /**
     * 调拨单管理根据主键获取到详情的列表
     * @param id 调拨单主键
     * @return Map<String,Object>
     */
    @RequestMapping(value = "/detailList.do")
    @ResponseBody
    public Map<String, Object> detailList(Integer id) {
        Map<String, Object> map = new HashMap<>(2);
        PageTbl page = this.getPage();
        PageUtils utils = allocationService.getPageDetailList(page, id);
        page.setTotalRows(utils.getTotalCount() == 0 ? 1 : utils.getTotalCount());
        //初始化分页对象
        executePageMap(map, page);
        map.put("rows", utils.getList());
        map.put("total", utils.getTotalPage() == 0 ? 1 : utils.getTotalPage());
        return map;
    }

    /**
     * 点击查看，跳转到详情列表页
     * @param id 调拨单主表主键
     * @return ModelAndView
     */
    @RequestMapping(value = "/toInfo.do")
    @ResponseBody
    public ModelAndView toInfo(Long id) {
        ModelAndView mv = this.getModelAndView();
        mv.addObject("info", allocationService.selectInfoById(id));
        mv.setViewName("techbloom/allo/alloinfo/alloinfo_info");
        return mv;
    }

    /**
     * 点击编辑，跳转到编辑页面
     * @param id 调拨单主键
     * @return ModelAndView
     */
    @RequestMapping(value = "/editInfo.do")
    @ResponseBody
    public ModelAndView editInfo(Long id) {
        ModelAndView mv = this.getModelAndView();
        mv.addObject("info", allocationService.selectInfoById(id));
        mv.setViewName("techbloom/allo/alloinfo/alloinfo_edit");
        return mv;
    }

    /**
     * 调拨单管理添加页面，点击保存  保存新增的调拨单
     * @param allocation 调拨单
     * @return Map<String,Object>
     */
    @RequestMapping(value = "/saveAllocation")
    @ResponseBody
    public Map<String, Object> saveAllocation(Allocation allocation) {
        Map<String, Object> map = new HashMap<>(3);
        allocation.setUserId(getUserId());
        Long id = allocationService.saveAllocation(allocation);
        map.put("result", id > 0);
        map.put("msg", id > 0 ? "保存成功！" : "保存失败！");
        map.put("allocationId", id);
        return map;
    }

    /**
     * 点击编辑，点击提交，修改状态
     * @param allocation 调拨单
     * @return Map<String,Object>
     */
    @RequestMapping(value = "/subAlloction")
    @ResponseBody
    public Map<String, Object> subAlloction(Allocation allocation) {
        return allocationService.subAllocation(allocation);
    }

    /**
     * 点击编辑，获取质保单号列表
     * @param  queryString 查询条件
     * @param warehouseId 仓库主键
     * @param factoryCode 厂区编码
     * @param pageSize 页码
     * @param pageNo 页面编号
     * @return Map<String,Object>
     */
    @RequestMapping(value = "/getQaCode")
    @ResponseBody
    public Map<String, Object> getQaCode(String queryString,Long warehouseId,String factoryCode, int pageSize, int pageNo ) {
        Map<String, Object> map = Maps.newHashMap();
        if (StringUtils.isNotEmpty(queryString)) {
            map.put("queryString", queryString);
        }
        map.put("warehouseCode", warehouseService.selectById(warehouseId).getCode());
        map.put("org", factoryCode);
        PageTbl page = this.getPage();
        page.setPagesize(pageSize);
        page.setPageno(pageNo);
        PageUtils utils = allocationService.getQaCode(page, map);
        map.put("result", utils.getList() == null ? "" : utils.getList());
        map.put("total", utils.getTotalPage() == 0 ? 1 : utils.getTotalPage());
        map.put("msg", "success");
        return map;
    }

    /**
     * 点击编辑，调拨单详情添加
     * @param qaCodeIds 详情质保号
     * @param factoryCode 调出厂区编码‘
     * @param outWarehouseId 调出仓库主键
     * @param factoryCodeIn 调入厂区编码
     * @param inWarehouseId 调入仓库主键
     * @param type 类型：add为新增，update为修改
     * @param allCode 调拨单号
     * @return Map<String,Object>
     */
    @RequestMapping(value = "/saveAlloctionDetail")
    @ResponseBody
    public Map<String, Object> saveAlloctionDetail(String[] qaCodeIds, String factoryCode, Long outWarehouseId, String factoryCodeIn, Long inWarehouseId,
                                                   String type, String allCode) {
        Allocation allocation = new Allocation();
        if (Constant.PAGE_TYPE_ADD.equals(type)){
            //新增时，allCode代表调拨单号
            if (StringUtils.isEmpty(allCode)){
                Warehouse outWarehouse = warehouseService.selectById(outWarehouseId);
                Warehouse inWarehouse = warehouseService.selectById(inWarehouseId);
                String serial = new DecimalFormat("0000").format(allocationService.selectLatestAllocation() + 1);
                allocation.setAllCode("DB" + DateUtils.getDays() + serial);
                allocation.setMoveTime(new Date());
                allocation.setInWarehouseCode(inWarehouse.getCode());
                allocation.setOutWarehouseCode(outWarehouse.getCode());
                allocation.setInWarehouseId(inWarehouse.getId());
                allocation.setOutWarehouseId(outWarehouse.getId());
                allocation.setFactoryCode(factoryCode);
                allocation.setInFactoryCode(factoryCodeIn);
                allocation.setUserId(getUserId());
                allocationService.insert(allocation);

                moveStorageService.updateSerial(serial,Constant.SERIAL_ALLO);
            }else {
                allocation = allocationService.selectOne(new EntityWrapper<Allocation>().eq("ALLCODE", allCode));
            }
        }else if (Constant.PAGE_TYPE_UPDATE.equals(type)){
            //修改时，allCode代表调拨单主键
            allocation = allocationService.selectById(allCode);
        }

        Map<String, Object> map = Maps.newHashMap();
        boolean result = allocationService.saveAllocationDetail(allocation.getId(), qaCodeIds,factoryCode,getUserId());
        map.put("result", result);
        map.put("msg", result ? "添加成功！" : "添加失败！");
        map.put("id", allocation.getId());
        map.put("allCode", allocation.getAllCode());
        return map;
    }

    /**
     * 删除调拨单明细数据
     * @param ids 调拨单明细主键
     * @return Map<String,Object>
     */
    @RequestMapping(value = "/deleteAllocationDetailIds")
    @ResponseBody
    public Map<String, Object> deleteAllocationDetailIds(String[] ids) {
        return allocationService.deleteAllocationDetailIds(ids);
    }

    /**
     * 列表页面点击删除，删除主表和详情的数据
     * @param ids 调拨单主键数组
     * @return Map<String,Object>
     */
    @RequestMapping(value = "/deleteByIds")
    @ResponseBody
    public Map<String, Object> deleteByIds(String[] ids) {
        return allocationService.deleteByIds(ids);
    }

    /**
     * 获取调入仓库的数据
     * @return Map<String,Object>
     */
    @RequestMapping(value = "/selectWarehouseIn.do")
    @ResponseBody
    public Map<String, Object> selectWarehouseIn() {
        Map<String, Object> map = new HashMap<>();
        map.put("queryString", request.getParameter("queryString"));
        PageTbl page = this.getPage();
        PageUtils utils = allocationService.selectWarehouseIn(page, map);
        page.setTotalRows(utils.getTotalCount() == 0 ? 1 : utils.getTotalCount());
        //初始化分页对象
        executePageMap(map, page);
        map.put("result", utils.getList());
        map.put("total", utils.getTotalPage() == 0 ? 1 : utils.getTotalPage());
        return map;
    }

    /**
     * 获取调出仓库下拉框
     * @return Map<String,Object>
     */
    @RequestMapping(value = "/selectWarehouseOut.do")
    @ResponseBody
    public Map<String, Object> selectWarehouseOut() {
        Map<String, Object> map = new HashMap<>(4);
        //okk
        map.put("factoryCode", Arrays.asList(getSessionUser().getFactoryCode().split(",")));
        map.put("queryString", request.getParameter("queryString"));
        PageTbl page = this.getPage();
        page.setPageno(Integer.parseInt(request.getParameter("pageNo")));
        PageUtils utils = allocationService.selectWarehouseOut(page, map);
        page.setTotalRows(utils.getTotalCount() == 0 ? 1 : utils.getTotalCount());
        //初始化分页对象
        executePageMap(map, page);
        map.put("result", utils.getList());
        map.put("total", utils.getTotalCount()== 0 ? 1 : utils.getTotalCount());
        return map;
    }

    /**
     * 导出Excel
     * @param request
     * @param response
     */
    @RequestMapping(value = "/toExcel.do", method = RequestMethod.POST)
    @ResponseBody
    public void materialExcel(HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> map = new HashMap<>(10);
        map.put("ids", StringUtils.stringToInt(request.getParameter("ids")));
        map.put("allCode", request.getParameter("queryAllCode"));
        map.put("startTime", request.getParameter("queryStartTime"));
        map.put("endTime", request.getParameter("queryEndTime"));
        map.put("factoryCodeOut", request.getParameter("queryFactoryCodeOut"));
        map.put("warehouseIdOut", request.getParameter("queryWarehouseOut"));
        map.put("factoryCodeIn", request.getParameter("queryFactoryCodeIn"));
        map.put("warehouseIdIn", request.getParameter("queryWarehouseIn"));
        map.put("creater", request.getParameter("queryCreater"));
        try {
            String sheetName = "调拨单" + "(" + DateUtils.getDay() + ")";
            response.setHeader("Content-Type", "application/force-download");
            response.setHeader("Content-Type", "application/vnd.ms-excel");
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Expires", "0");
            response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
            response.setHeader("Pragma", "public");
            response.setHeader("Content-disposition", "attachment;filename=" + new String(sheetName.getBytes("gbk"),
                    "ISO8859-1") + ".xls");

            Map<String, String> mapFields = new LinkedHashMap<>();
            String [] excelIndexArray = request.getParameter("queryExportExcelIndex").split(",");

            if (excelIndexArray.length==1&&"".equals(excelIndexArray[0])) {
                mapFields.put("allCode", "调拨单号");
                mapFields.put("moveTimeStr", "单据创建时间");
                mapFields.put("factoryName", "调出厂区");
                mapFields.put("inFactoryName", "调入厂区");
                mapFields.put("outWarehouseName", "调出仓库");
                mapFields.put("inWarehouseName", "调入仓库");
                mapFields.put("startOutTimeStr", "调拨开始时间");
                mapFields.put("endInTimeStr", "调拨结束时间");
                mapFields.put("userName", "创建人工号");
                mapFields.put("alloState", "单据状态");
            }else {
                for (String s : excelIndexArray) {
                    if ("2".equals(s)) {
                        mapFields.put("allCode", "调拨单号");
                    } else if ("3".equals(s)) {
                        mapFields.put("moveTimeStr", "单据创建时间");
                    } else if ("4".equals(s)) {
                        mapFields.put("factoryName", "调出厂区");
                    } else if ("5".equals(s)) {
                        mapFields.put("inFactoryName", "调入厂区");
                    } else if ("6".equals(s)) {
                        mapFields.put("outWarehouseName", "调出仓库");
                    } else if ("7".equals(s)) {
                        mapFields.put("inWarehouseName", "调入仓库");
                    } else if ("8".equals(s)) {
                        mapFields.put("startOutTimeStr", "调拨开始时间");
                    } else if ("9".equals(s)) {
                        mapFields.put("endInTimeStr", "调拨结束时间");
                    } else if ("10".equals(s)) {
                        mapFields.put("userName", "创建人工号");
                    } else if ("11".equals(s)) {
                        mapFields.put("alloState", "单据状态");
                    }
                }
            }

            DeriveExcel.exportExcel(sheetName, allocationService.getAlloStorageOutExcel(map), mapFields, response, "");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 导出调拨明细查看页Excel
     * @param request
     * @param response
     */
    @RequestMapping(value = "/detailExcel.do", method = RequestMethod.POST)
    @ResponseBody
    public void detailExcel(HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> map = new HashMap<>(3);
        map.put("ids",StringUtils.stringToInt(request.getParameter("ids")));
        map.put("id", request.getParameter("infoid"));
        try {
            String sheetName = "调拨单详情" + "(" + DateUtils.getDay() + ")";
            response.setHeader("Content-Type", "application/force-download");
            response.setHeader("Content-Type", "application/vnd.ms-excel");
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Expires", "0");
            response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
            response.setHeader("Pragma", "public");
            response.setHeader("Content-disposition", "attachment;filename=" + new String(sheetName.getBytes("gbk"),
                    "ISO8859-1") + ".xls");

            Map<String, String> mapFields = new LinkedHashMap<>();
            mapFields.put("qaCode", "质保单号");
            mapFields.put("batchNo", "批次号");
            mapFields.put("outShelfCode", "调出库位");
            mapFields.put("inShelfCode", "调入库位");
            mapFields.put("materialCode", "物料编码");
            mapFields.put("meter", "数量");
            mapFields.put("drumType", "盘类型");
            mapFields.put("model", "盘规格");
            mapFields.put("outerDiameter", "盘外径 ");
            mapFields.put("innerDiameter", "盘内径");
            mapFields.put("stateStr", "调拨状态");

            mapFields.put("allCode", "调拨单号");
            mapFields.put("movetime", "单据创建时间");
            mapFields.put("factoryName", "调出厂区");
            mapFields.put("inFactoryName", "调入厂区");
            mapFields.put("outWarehouseName", "调出仓库");
            mapFields.put("inWarehouseName", "调入仓库");

            DeriveExcel.exportExcel(sheetName, allocationDetailService.getAlloStorageOutDetailExcel(map), mapFields, response, "");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
